package com.jun.seckill_by_jun.service;

import com.jun.seckill_by_jun.domain.OrderInfo;
import com.jun.seckill_by_jun.domain.SeckillOrder;
import com.jun.seckill_by_jun.domain.SeckillUser;
import com.jun.seckill_by_jun.redis.RedisService;
import com.jun.seckill_by_jun.redis.SeckillKey;
import com.jun.seckill_by_jun.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SeckillService {
    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    RedisService redisService;

    @Transactional
    public OrderInfo seckill(SeckillUser user, GoodsVo goods) {
        boolean success = goodsService.reduceStock(goods);
        if(success){
            return orderService.createOrder(user,goods);
        }else{
            setGoodsOver(goods.getId());
            return null;
        }
    }

    public long getSeckillResult(Long id, long goodsId) {
        SeckillOrder order = orderService.getOrderByUserIdGoodsId(id, goodsId);
        if(order != null){
            return order.getOrderId();
        }else{
            boolean isOver = getGoodsOver(goodsId);
            if(isOver){
                return -1;
            }else{
                return 0;
            }
        }

    }
    private void setGoodsOver(Long goodsId){
        redisService.set(SeckillKey.isGoodsOver,""+goodsId,true);
    }

    private boolean getGoodsOver(long goodsId) {
        return redisService.exists(SeckillKey.isGoodsOver,""+goodsId);
    }
}
